class PlanMgrController {
    def authenticateService
    def teacherService
    def valueLevelService
    def index = { }

    def planShow = {
        Classes c = Classes.get(params.classesid)

        def planList = Plan.findAllByClasses(c);
        return  [planList: planList,classesid:params.classesid]
    }

    def setPlanAndShow = {
        Classes c = Classes.get(params.classesid)

        def planList = Plan.findAllByClasses(c)
        // 待选择的课程与老师
        def courselst = valueLevelService.getCodeListByLevel(c.level)

        def teacherList = teacherService.getSchoolAndAbeldTeacher(session.school);
        def teacherlst = new HashMap() 
        courselst.each{ acourse ->
                def templist = new ArrayList()
                teacherList.each{aTeacher ->
                     aTeacher.course.any{elem ->
                        if(elem == acourse.code){
                             templist.add(aTeacher)
                        }                    
                     }                
                }
                teacherlst.put(acourse.code,templist)
        }
        return  [planList: planList,classesid:params.classesid,courselst:courselst,teacherlst:teacherlst]
    }

    def delete = {
        Classes c = Classes.get(params.classesid)
        def planList = Plan.findAllByClasses(c)
        planList.each{
            it.delete(flush:true)
        }
        return redirect(action: "setPlanCondition",params:[classesid:params.classesid])
    }

    // 登录用户查看自己的课表
    def iplanShow = {
        
        [restTimeList:RestTime.findAllBySchool(session.school),planList:Plan.findAllByTeacher(authenticateService.userDomain())]
    }

        // 登录用户查看自己的课表
    def iplanPrint = {
        
        [restTimeList:RestTime.findAllBySchool(session.school),planList:Plan.findAllByTeacher(authenticateService.userDomain())]
    }

     // 首页显示课表
    def myPlan = {
        def restTimeList = new ArrayList()
        def planList = new ArrayList()
        if(session.school){
           restTimeList = RestTime.findAllBySchool(session.school)           
        }
        if(authenticateService.isLoggedIn()){
            planList = Plan.findAllByTeacher(authenticateService.userDomain())
        }
        
        [restTimeList:restTimeList,planList:planList]
        
//        [restTimeList:RestTime.findAllBySchool(session.school),planList:Plan.findAllByTeacher(authenticateService.userDomain())]
    }

    // 打印课表
    def planPrint = {
        
        Classes c = Classes.get(params.classesid)

        def planList = Plan.findAllByClasses(c);
        return  [planList: planList,classesid:params.classesid,classesInstance:c]
    }

    def classeslist = {
        
    }

    // 自动生成课表的预设项目
    def setPlanCondition = {
        def c = Classes.get(params.classesid)
        def planListCount = Plan.countByClasses(c) 
        School school = session.school
        def  schoolRestTimes = RestTime.findAllBySchool(school)
        if(planListCount < 1){    
            for (int i=1;i<6;i++) { 
                schoolRestTimes.each{
                    Plan planinstance = new Plan()
                    planinstance.classes = c
                    planinstance.week = i
                    planinstance.teacher = null
                    planinstance.course = ''
                    planinstance.school = school
                    planinstance.restTime = it
                    planinstance.save(flush:true)
                }                
            }
        }
        // 待选择的课程与老师
        def courselst = valueLevelService.getCodeListByLevel(c.level)

        def teacherList = teacherService.getSchoolAndAbeldTeacher(session.school);
        def teacherlst = new HashMap() 
        courselst.each{ acourse ->
                def templist = new ArrayList()
                teacherList.each{aTeacher ->
                     aTeacher.course.any{elem ->
                        if(elem == acourse.code){
                             templist.add(aTeacher)
                        }                    
                     }                
                }
                teacherlst.put(acourse.code,templist)
        }
        def planlst = Plan.findAllByClasses(c)
        // 
        def teacherCourseGroup = planlst.groupBy{
            it.course
        }

        def selectPlanTime = planlst.grep{
            it.teacher != null && it.course != ""
        }
        return  [classesInstance:c,selectPlanTime:selectPlanTime.size(),planListCount: Plan.countByClasses(c),courselst:courselst,teacherlst:teacherlst,classesid:params.classesid,teacherCourseGroup:teacherCourseGroup]
    }




    def planList = {
        Classes c = Classes.get(params.classesid)
        def planListCount = Plan.countByClasses(c) 
        School school = session.school
        def  schoolRestTimes = RestTime.findAllBySchool(school)
        if(planListCount < 1){    
            for (int i=1;i<6;i++) { 
                schoolRestTimes.each{
                    Plan planinstance = new Plan()
                    planinstance.classes = c
                    planinstance.week = i
                    planinstance.teacher = null
                    planinstance.course = ''
                    planinstance.school = school
                    planinstance.restTime = it
                    planinstance.save(flush:true)
                }                
            }
        }
        def planList = Plan.findAllByClasses(c);
        // 待选择的课程与老师
        def courselst = valueLevelService.getCodeListByLevel(c.level)

        def teacherList = teacherService.getSchoolAndAbeldTeacher(session.school);
        def teacherlst = new HashMap() 
        courselst.each{ acourse ->
                def templist = new ArrayList()
                teacherList.each{aTeacher ->
                     aTeacher.course.any{elem ->
                        if(elem == acourse.code){
                             templist.add(aTeacher)
                        }                    
                     }                
                }
                teacherlst.put(acourse.code,templist)
        }
        return  [planList: planList,restTimeCount:schoolRestTimes.size(),courselst:courselst,teacherlst:teacherlst,classesid:params.classesid]
    }

//////////////////////
    def resetSave = {
 
        def aCourseAndTeacher = params.courseAndTeacher
        
        aCourseAndTeacher.each{
              if(it != ""){
                 log.info(it)
                 def aCourseTeacher = it.tokenize(',')
                 log.info(aCourseTeacher)
                 if(aCourseTeacher[0] != ""){
                     def planInstance = Plan.get(aCourseTeacher[0].trim().toLong())
                     if(planInstance){
                         if(aCourseTeacher[1] && aCourseTeacher[2]){      
                             Teacher t = Teacher.get(aCourseTeacher[1].trim().toLong())
                             if(t){
                                   planInstance.teacher = t
                                   planInstance.course = aCourseTeacher[2]
                             }
                         }else{
                             planInstance.teacher = null
                             planInstance.course = ""
                         }
                         planInstance.save(flush:true) 
                     }
                  }      
            }
        }
        def classes = Classes.get(params.classesid)

        TeacherCourseClasses.findAllByClasses(classes).each{
            it.delete(flush:true)
        }
        
        def teacherList = Plan.findAllByClasses(classes).groupBy{
            it.course
        }
        if(teacherList.size() > 0){
            teacherList.each{
                if(it.key != ""){
                    TeacherCourseClasses teachercc = new TeacherCourseClasses()
                    teachercc.course = it.key
                    teachercc.teacher = it.value[0].teacher
                    teachercc.classes = classes
                    teachercc.save()
                }
            }
        } 

        
        flash.message = "保存课表成功！"
        redirect(action:"planShow",params:[classesid:params.classesid])
    }
///////////////////////////////


    def save = {
        def c = Classes.get(params.classesid)
        def planList = Plan.findAllByClasses(c)

        planList.each{
            it.teacher = null
            it.course = ""
            it.save(flush:true)
        }
        // 判断老师是否在某一个课时有课，
        //1 首先找到可上课的课时最少的哪个老师
        //2 再次找到教师课上课时的一个planlist,然后进行排课
        //if(){}
        def com = [compare: 
        {
        a,b ->
        a>b?-1:1 
        }] as Comparator 

        def teacherCourseMap = new TreeMap(com)
        params.teacherCourses.each{
            if(it != ""){
                def aCourseTeacher = it.tokenize(',')                
                def teaherPlanCount = Plan.countByTeacher(Teacher.get(aCourseTeacher[0].toLong()))
                teacherCourseMap.put(teaherPlanCount,aCourseTeacher[1])
            }
        }
        log.info(teacherCourseMap) 

        
        params.teacherCourses.each{
            def aCourseTeacher = it.tokenize(',')
            teacherCourseMap.each{elem ->
                if(elem.value.trim() == aCourseTeacher[1]){
                    def teaherPlanList = Plan.findAllByTeacher(Teacher.get(aCourseTeacher[0].toLong()))
                    def teacherNoCoursePlanList = planList.grep{ aPlan ->
                        teaherPlanList.every{ aTeacherPlan ->
                            aTeacherPlan.week+aTeacherPlan.restTime.id != aPlan.week + aPlan.restTime.id                  
                        }
                    }
                    saveACourseTeacher(aCourseTeacher,teacherNoCoursePlanList,params.classesid)
                }
            }
        }

        saveClassesTeacherCourse(params.classesid)

        redirect(action: "setPlanAndShow",params:[classesid:params.classesid])
    }

    private saveClassesTeacherCourse(classesid){
        def classes = Classes.get(classesid)
            TeacherCourseClasses.findAllByClasses(classes).each{
                it.delete(flush:true)
            }
            def teacherList = Plan.findAllByClasses(classes).groupBy{
                it.course
            }
            if(teacherList.size() > 0){
                teacherList.each{
                    if(it.key != ""){
                        TeacherCourseClasses teachercc = new TeacherCourseClasses()
                        teachercc.course = it.key
                        teachercc.teacher = it.value[0].teacher
                        teachercc.classes = classes
                        teachercc.save()
                    }
                }
            } 
    }
    // 
    private saveACourseTeacher(courseTeacher,planList,classesid) { 
         def teacherId = courseTeacher[0].toLong()
        def course = courseTeacher[1].toString()
        def priod = courseTeacher[2].toInteger()
        if(planList.size() > 0){
            // 首先取出没有课的课时列表
            def noCoursePlanList = planList.grep{
                it.teacher == null || it.course == ""
            }
            // 用周来进行分组，便于后面把课都平均分配到不同的天去
            def groupWeekPlanList = noCoursePlanList.groupBy{
                it.week
            }
            // 循环按周分配的组，将课程分配进去
            if(priod > groupWeekPlanList.size()){       
                def selectedPlanList = new ArrayList()
                def seletedCourseLength = priod - groupWeekPlanList.size()
                 
                int loopNum = (groupWeekPlanList.size()==0) ? 0 : (priod/groupWeekPlanList.size())
                def loopNumLast = (groupWeekPlanList.size()==0) ? 0 : priod%groupWeekPlanList.size()
                if(loopNum > 0){
                    for(int i=0;i<loopNum;i++){
                        selectedPlanList.addAll(saveGroupWeekPlan(groupWeekPlanList,teacherId,course))
                    }
                }
//                if(loopNum > 1 || loopNumLast > 0){
                if(loopNumLast > 0){
                    def noselectedPlanList = noCoursePlanList.grep{
                        selectedPlanList.every{ elem->
                            it.id.toString() != elem.toString()
                        }
                    }
                    def noSelectedGroupWeekPlanList = noselectedPlanList.groupBy{
                        it.week
                    }
                    saveGroupWeekPlanRandom(noSelectedGroupWeekPlanList,teacherId,course,seletedCourseLength)
                }
            }else{ 
                saveGroupWeekPlanRandom(groupWeekPlanList,teacherId,course,priod)
            }
            
        }        
        //return redirect(action: "planShow",params:[classesid:classesid])
	}

    // 超过每周上课天数的，按照每天去分配
    private ArrayList saveGroupWeekPlan(groupWeekPlanList,teacherId,course){
          def selectedPlanList = new ArrayList()
          groupWeekPlanList.each{
                def randomNum = Math.round((Math.random()*(it.value.size()-1)))
                Plan p = Plan.get(it.value[randomNum.toInteger()].id)
                p.teacher = Teacher.get(teacherId)
                p.course = course
                p.save()
                selectedPlanList.add(it.value[randomNum.toInteger()].id)
            }
            return selectedPlanList
    }

    // 未超过每周上课天数的，随机去分配
    private ArrayList saveGroupWeekPlanRandom(groupWeekPlanList,teacherId,course,priod){
            def selectedPlanList = new ArrayList()
            def weekList = groupWeekPlanList.grep{
                it.key
            }
            Collections.shuffle(weekList);
            for(int i=0;i<priod;i++){
                def aGroup = groupWeekPlanList[weekList[i].key]
 
                def randomNum = Math.round((Math.random()*(aGroup.size()-1)))
                Plan p = Plan.get(aGroup[randomNum.toInteger()].id)
                p.teacher = Teacher.get(teacherId)
                p.course = course
                p.save()
                selectedPlanList.add(aGroup[randomNum.toInteger()].id)
            }
            return selectedPlanList
    }

    private getRandomArray(sourceList,returnNum){
 
//        def randomList = new long[returnNum]
//        def randomNum = Math.round((Math.random()*(sourceList.size()-1)))

//         boolean[] bol = new boolean[returnNum];
//          for(int i=1;i<(returnNum+1);i++)
//              bol[i] = false;
//              bol[0]=true;
//              for (int i = 0; i < returnNum; ) {
//                   def randomNum = Math.round((Math.random()*(sourceList.size()-1)))
//                   if(bol[randomNum.toInteger()])
//                        continue;
//                   bol[randomNum]= true;
//                   i++;
//                   log.info(randomNum+"   ");
//              } 
    }
}
